package cn.didi.feidi.androidorder.fragment.personal;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.jungly.gridpasswordview.GridPasswordView;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.util.MD5Util;

/**
 * Created by king on 2017/8/28.
 */

public class PersonWalletPayPasswordFirstSetFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonWaPayPaFirstSet";

    //    标识此次的修改的签名
    private String sign = "";


    private final static int SECOND_STEP = 2;
    private final static int THREE_STEP = 3;

    private final static int FINISH = 4;

    private TextView changePasswordTip;
    private TextView changePasswordTip2;
    private GridPasswordView gridPasswordView;
    private TextView saveNewPasswordBtn;

    private int whereStep = SECOND_STEP;

    private String newPasswordOne;
    private String newPasswordTwo;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonWalletPayPasswordFirstSetFragment newInstance(Bundle bundle) {
        PersonWalletPayPasswordFirstSetFragment fragment = new PersonWalletPayPasswordFirstSetFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_wallet_pay_password_first_set, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        changePasswordTip = (TextView) rootView.findViewById(R.id.person_wallet_change_pay_password_tip);
        changePasswordTip2 = (TextView) rootView.findViewById(R.id.person_wallet_change_pay_password_tip2);
        gridPasswordView = (GridPasswordView) rootView.findViewById(R.id.person_wallet_change_pay_password_gridpassword_view);

        saveNewPasswordBtn = (TextView) rootView.findViewById(R.id.save_feidi_pay_password_btn);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addListener() {
        gridPasswordView.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {

            }

            @Override
            public void onInputFinish(String psw) {
                if (whereStep == SECOND_STEP) {
                    newPasswordOne = psw;
                    gridPasswordView.clearPassword();
                    changePasswordTip.setText("再次填写以确认");
                    changePasswordTip2.setVisibility(View.GONE);
                    saveNewPasswordBtn.setVisibility(View.VISIBLE);
                    whereStep = THREE_STEP;
                } else {
                    if (whereStep == THREE_STEP) {
                        newPasswordTwo = psw;
                        if (!newPasswordOne.equals(newPasswordTwo)) {
                            makeToast("新密码输入不一致");
                            whereStep = SECOND_STEP;
                            gridPasswordView.clearPassword();
                            changePasswordTip.setText("请设定新密码");
                            changePasswordTip2.setVisibility(View.VISIBLE);
                            saveNewPasswordBtn.setVisibility(View.GONE);
                        } else {
                            InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (inputMethodManager.isActive()) {
                                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
                            }
                            whereStep = FINISH;
                        }
                    }
                }
            }
        });

        gridPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (whereStep == FINISH) {
                    makeToast("不可再次编辑");
                }
            }
        });

        saveNewPasswordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (whereStep == FINISH) {
                    setNewPayPasswordInServer();
                } else {
                    return;
                }
            }
        });
    }

    private void setNewPayPasswordInServer(){
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("newPayPwd", MD5Util.GetMD5Code32Bit(newPasswordTwo));

        executeRequest(new AppActionRequest<>(Api.SET_FIRST_PAY_PWD, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                makeToast("已设置新密码");
                UserManager.setPayPassword(true);
                getActivity().finish();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                makeToast("密码设置失败");
                getActivity().finish();

                switch (errorEvent) {
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }
}
